package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.common.AliYun;
import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.seller.*;
import com.dongdongshop.service.GoodsService;
import com.dongdongshop.service.ItemCatService;
import com.dongdongshop.service.SpecificationOptionService;
import com.dongdongshop.service.TemplateService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.dongdongshop.common.SpecVo;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("goods")
public class GoodsController {

    private final Logger logger= LoggerFactory.getLogger(GoodsController.class);
    @Reference
    private ItemCatService itemCatService;
    @Reference
    private TemplateService templateService;
    @Reference
    private GoodsService goodsService;
    @Reference
    private SpecificationOptionService specificationOptionService;

    @RequestMapping("toGoodsEdit")
    public String toGoodsEdit(){
        return "admin/goods_edit";
    }

    //一级二级三级
    @RequestMapping("getOne/{parentId}")
    @ResponseBody
    public Result getOne(@PathVariable("parentId")Long parentId){
        try {
            List<TbItemCat> list=itemCatService.getOne(parentId);
            return Result.response(ResultEnum.OK).setData(list);
        }catch (Exception e){
            logger.info("操作失败",e);
            return Result.response(ResultEnum.FAIL);
        }
    }
    //获取模板id：
    @RequestMapping("getTypeId/{id}")
    @ResponseBody
    public Result getTypeId(@PathVariable("id")Long id){
        try {
            Long typeId=itemCatService.getTypeId(id);
            return Result.response(ResultEnum.OK).setData(typeId);
        }catch (Exception e){
            logger.info("操作失败",e);
            return Result.response(ResultEnum.FAIL);
        }
    }
    //获取模板id对应的品牌
    @RequestMapping("getItemTemplate/{typeId}")
    @ResponseBody
    public Result getItemTemplate(@PathVariable("typeId")Long typeId){
        try {
            TbTypeTemplate tbTypeTemplate=templateService.updateById(typeId);
            return Result.response(ResultEnum.OK).setData(tbTypeTemplate);
        }catch (Exception e){
            logger.info("操作失败",e);
            return Result.response(ResultEnum.FAIL);
        }
    }

    @RequestMapping("addGood")
    @ResponseBody
    public Result addGood(TbGoods goods, TbGoodsDesc desc,String itemListJson){
        //System.out.println(1111);
       // System.out.println("---------"+itemListJson);
        try {
            //获取商家id
            TbSeller tbSeller =(TbSeller) SecurityUtils.getSubject().getPrincipal();
            goods.setSellerId(tbSeller.getSellerId());
            String sellerName=tbSeller.getName();
            goods.setAuditStatus("0");
            List<TbItem> list = JSON.parseArray(itemListJson, TbItem.class);
            int i=goodsService.addGood(goods,desc,list,sellerName);
         //   System.out.println("输出结果"+i);
            if (i>0){
                return Result.response(ResultEnum.OK);
            }else {
                return Result.response(ResultEnum.FAIL);
            }
        }catch (Exception e){
            logger.info("操作失败",e);
            return Result.response(ResultEnum.FAIL);
        }
    }

    //查询规格
    @RequestMapping("getSpecAndOption")
    @ResponseBody
    public Result getSpecAndOption(@RequestParam("typeId")Long typeId) {
        //根据id查询模板
        TbTypeTemplate tbTypeTemplate = templateService.updateById(typeId);
        //解析模板中的规格信息
        List<SpecVo> specDTOList = JSONObject.parseArray(tbTypeTemplate.getSpecIds(), SpecVo.class);
        //循环调用根据规格查询出规格选项并组装数据
        for (SpecVo spec : specDTOList) {
            List<TbSpecificationOption>  options =  specificationOptionService.listOptionsBySpecId(spec.getId());
            spec.setOptions(options);

        }
        return Result.response(ResultEnum.OK).setData(specDTOList);
    }

    @RequestMapping("upLoadFile")
    @ResponseBody
    public Result upLoadFile(@RequestParam(value = "myFile")MultipartFile myFile) {
        try{
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = AliYun.ENDPOINT;
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = AliYun.ACCESSKEYID;
        String accessKeySecret = AliYun.ACCESSKEYSECRET;
        String bucketName = AliYun.BUCKETNAME;
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        String objectName = myFile.getOriginalFilename();//上传文件的路径

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        //String content = "Hello OSS";
        String url = null;//前台路径
        try {
            ossClient.putObject(bucketName, objectName, myFile.getInputStream());
            //拼接图片访问路径
            url = "http://" + bucketName + AliYun.POINT+ objectName;

        } catch (IOException e) {
            e.printStackTrace();
            return Result.response(ResultEnum.FAIL);
        }

// 关闭OSSClient。
        ossClient.shutdown();
        return Result.response(ResultEnum.OK).setData(url);
    }catch (Exception e){
            logger.info("操作异常",e);
            return Result.response(ResultEnum.FAIL);
        }
    }
}
